package com.guoguo.cloudmusic.ui.common.Adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

/**
 * 封装的 RecyclerView adapter
 * @see https://www.dazhuanlan.com/auraty/topics/1615762
 * @author GuoGuo
 * @date 2021/12/12 1:20 下午
 */
//https://blog.csdn.net/renlei0012/article/details/90294103?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0.queryctrv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3

open class KtAdapter<T> constructor(
    private val layoutId: Int,
    private val itemList: List<T>,
    private val bindHolder: View.(T) -> Unit
) : RecyclerView.Adapter<KtAdapter.ViewHolder>() {
    private var itemClick: T.() -> Unit = {}

    constructor(
        layoutId: Int,
        itemList: List<T>,
        bindHolder: View.(T) -> Unit,
        itemClick: T.() -> Unit = {}
    ) : this(layoutId, itemList, bindHolder) {
        this.itemClick = itemClick
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(layoutId, parent,false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = itemList[holder.absoluteAdapterPosition]
        holder.itemView.bindHolder(item)
        holder.itemView.setOnClickListener {
            itemOnClick(it, position)
        }
    }

    override fun getItemCount() = itemList.size

    // 在本类与子类中可见 private 只在本类中可见
    protected open fun itemOnClick(it: View, position: Int) {
        itemList[position].itemClick()
    }
}